package com.lvshi0797.cms.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lvshi0797.cms.dto.AjaxObj;
import com.lvshi0797.cms.entities.FManager;
import com.lvshi0797.cms.helper.BussinessException;
import com.lvshi0797.cms.helper.Captcha;
import com.lvshi0797.cms.service.IManagerService;

@Controller
public class LoginController {
	@Autowired
	private IManagerService managerService;
	
	@RequestMapping("dologin")
	@ResponseBody
	public AjaxObj login(HttpSession session,String username,String password,String captcha){
		String cc = (String) session.getAttribute("cc");
		if(captcha==null||!captcha.equals(cc)){
			return new AjaxObj(0,"验证码出错！");
		}
		FManager manager = null;
		try {
			manager = managerService.login(username, password);
		} catch (BussinessException e) {
			return new AjaxObj(0,e.getMessage());
		}
		session.setAttribute("user", manager);
		return new AjaxObj(1,"登录成功！");
	}
	
	@RequestMapping("logout")
	@ResponseBody
	public AjaxObj logout(HttpSession session){
		session.setAttribute("user", null);
		return new AjaxObj(1,"退出成功！");
	}
	
	@RequestMapping("/drawCheckCode")
	public void drawCheckCode(HttpServletResponse resp,HttpSession session) throws IOException {
		resp.setContentType("image/jpg");
		int width = 200;
		int height = 30;
		Captcha c = Captcha.getInstance();
		c.set(width, height);
		String checkcode = c.generateCheckcode();
		session.setAttribute("cc", checkcode);
		OutputStream os = resp.getOutputStream();
		ImageIO.write(c.generateCheckImg(checkcode), "jpg", os);
	}
	
 
	
	
}
